package controllers

import (
	"strings"
	"time"

	"openapi/errorcode"

	"github.com/astaxie/beego"
	log "github.com/cihub/seelog"
)

/*
	最基础验证,只做AppKey的存在性检验
*/
type BaseController struct {
	beego.Controller
	Resp      map[string]interface{} //输出结果
	StartTime time.Time              //开始时间
	AppKey    string                 //AppKey值
	Scheme    string                 //协议的类型http,https
}

/*
	在Method方法前调用该函数
*/
func (p *BaseController) Prepare() {
	p.StartTime = time.Now()
	p.Resp = make(map[string]interface{})
	p.AppKey = p.GetString("appkey", "")
	p.Scheme = p.Ctx.Input.Header("X-Scheme")
}

func (p *BaseController) ForceHTTPS() {
	if p.Scheme != "https" {
		p.Resp["code"] = errorcode.EC_GL_INVALID_HTTPS
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_INVALID_HTTPS)
		p.Output("Prepare(Https)")
		p.StopRun()
	}
}

func (p *BaseController) Output(funcName string) {
	timeend := time.Since(p.StartTime)
	log.Infof("%s, ip: %s, %s %s, cost: %s, resp:(%d, %s)", funcName,
		p.Ctx.Input.IP(), p.Ctx.Input.Method(), p.Ctx.Input.URI(),
		timeend.String(), p.Resp["code"], p.Resp["msg"])
	p.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	p.Data["json"] = p.Resp
	p.ServeJSON()
}

/*
	判断是否管理员权限,可以适当放宽权限
*/
func (p *BaseController) PriorityVisit() bool {
	return p.isInternalIP(p.Ctx.Input.IP())
}

func (p *BaseController) isInternalIP(clientIP string) bool {
	return strings.HasPrefix(clientIP, "10.") ||
		clientIP == "127.0.0.1" ||
		clientIP == "0.0.0.0"
}
